package edu.hawaii.duedates.library;

import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import com.meterware.httpunit.GetMethodWebRequest;
import com.meterware.httpunit.HttpUnitOptions;
import com.meterware.httpunit.WebConversation;
import com.meterware.httpunit.WebForm;
import com.meterware.httpunit.WebLink;
import com.meterware.httpunit.WebRequest;
import com.meterware.httpunit.WebResponse;
import com.meterware.httpunit.WebTable;
import edu.hawaii.duedates.BorrowedItem;
import edu.hawaii.duedates.Lender;

/**
 * This class is built for actions related to the Hawaii State Library system. It is also implements
 * the Lender interface. Must have login and getInfo.
 * 
 * @author John Ly
 * @author John Zhou
 */
public class HawaiiState implements Lender {

  /**
   * Attempts to login to the Hawaii State Library System.
   * 
   * @param id The Hawaii library id barcode.
   * @param password The password (last four digits of your phone number).
   * @return The WebConversation after logging in.
   * @throws Exception If errors occur while logging in.
   */
  public WebConversation login(String id, String password) throws Exception {
    try {
      String url = "http://www.librarieshawaii.org/";
      // Website has bogus JavaScript code.
      HttpUnitOptions.setExceptionsThrownOnScriptError(false);
      // create the conversation object which will maintain state for us
      WebConversation conversation = new WebConversation();
      WebRequest request = new GetMethodWebRequest(url);
      WebResponse response = conversation.getResponse(request);
      WebLink link = response.getLinkWith("My Account");
      link.click();
      response = conversation.getCurrentPage();
      WebForm form = response.getForms()[0];
      //form.setParameter("sec1", "0011429495");
      //form.setParameter("sec2", "3845");
      form.setParameter("sec1", id);
      form.setParameter("sec2", password);
      form.submit();
      return conversation;
    }
    catch (Exception e) {
      throw new Exception("Error while logging in to Hawaii State Library", e);
    }
  }

  /**
   * Gets info from the Hawaii State Library site.
   * 
   * @param id The barcode number from the library card.
   * @param password The password (normally the last four digits of your phone number).
   * @param bookList The List to add books to, contains books from other libraries.
   * @return The List that contains the newly added books.
   * @throws Exception If problems occur getting the information.
   */
  public List<BorrowedItem> 
    getInfo(String id, String password, List<BorrowedItem> bookList) throws Exception {
    try {
      String dueDate = "";
      String bookTitle = "";
      WebConversation conversation = this.login(id, password);
      WebResponse response = conversation.getCurrentPage();
      WebLink link = response.getLinkWith("Items Out");
      link.click();
      response = conversation.getCurrentPage();
      boolean noBooksOut = response.getText().contains("Checked Out: 0");
      if (noBooksOut) {
        return bookList;
      }      
      WebTable table = response.getTableStartingWith("Title");
      for (int i = 1; i < table.getRowCount(); i++) {
        dueDate = table.getCellAsText(i, 2);
        bookTitle = table.getCellAsText(i, 0);
        bookTitle = bookTitle.replace("|", "");
        bookTitle = bookTitle.replace("\n", "");
        bookTitle = bookTitle.trim();
        Calendar cal = convertDateToCalendar(dueDate);
        BorrowedItem book = new BorrowedItem(bookTitle, cal, "Book", "Hawaii State");
        bookList.add(book);
      }
    }
    catch (Exception e) {
      throw new Exception("Error getting Hawaii State Library info", e);
    }
    return bookList;
  }
  
  /**
   * Converts the HawaiiState date string (mm/dd/yyyy) into a Calendar object.
   * @param hiLibDate The date string in the format mm/dd/yyyy.
   * @return The Calendar object based on the date string.
   * @throws Exception If the string cannot be parsed.
   */
  public Calendar convertDateToCalendar(String hiLibDate) throws Exception {
    int monthPos = 0;
    int dayPos = 3;
    int yearPos = 6;
    int month = Integer.parseInt(hiLibDate.substring(monthPos, monthPos + 2));
    int day = Integer.parseInt(hiLibDate.substring(dayPos, dayPos + 2));
    int year = Integer.parseInt(hiLibDate.substring(yearPos));
    Calendar cal = Calendar.getInstance(Locale.US);
    cal.set(Calendar.MONTH, month - 1);
    cal.set(Calendar.DAY_OF_MONTH, day);
    cal.set(Calendar.YEAR, year);
    cal.set(Calendar.HOUR_OF_DAY, 23);
    cal.set(Calendar.MINUTE, 59);
    cal.set(Calendar.SECOND, 59);
    cal.set(Calendar.MILLISECOND, 0);
    return cal;

  }

}
